$(function () {
    findById();
})

function findById() {
    // let  url="/html/user/userEdit.html?id=3";
    // let id=aa(url)=id=3
    let id = sessionStorage.getItem("userid");
    $.ajax({
        url: "/back/user/findById",
        data: {id: id},
        dataType: 'json',
        type: 'get',
        success: function (data) {
            console.log(data);
            setData(data.model);

        }

    })
}

function setData(data) {
    $("#username").val(data.username);
    $("#phone").val(data.phone);
    $("#weight").val(data.weight);
    $("#email").val(data.email);
    $("input[type=radio][name=isRecommend][value=" + data.sex + "]").attr("checked", true);
    setHobby(data.hobby);

}
function setHobby(hobby) {
    let hobbys = hobby.split(",");
    $('input:checkbox[name=hobby]').each(function () {

        for (let i = 0; i < hobbys.length; i++) {
            if ($(this).val() == hobbys[i]) {
                $(this).attr("checked", true);
            }
        }
    });
}
function save() {
    let da = {
        id:sessionStorage.getItem("userid"),
        username: $("#username").val(),
        phone: $("#phone").val(),
        weight: $("#weight").val(),
        email: $("#email").val(),
        sex: $('input:radio[name=sex]:checked').val(),
        hobby: getHobby(),
        birthday: $("#birthday").val()
    };
    // console.log(data);
    $.ajax({
        url: '/back/user/edit',//对应的是后台servlet的webServlet的注解
        data: da,//da 前端传递到后端的数据
        type: 'post',
        dataType: 'json',//注意：T大写
        success: function (data) {//后端响应给前台的数据

            if (data.result == 'success') {
                findAll();
                closeWindow();
                // $(".right").load("/html/user/userManage.html")
            } else if (data.result == 'isHave') {
                $("#username").focus();
                alert("该名称已存在");
            } else {
                alert("修改失败");
            }
        }
    });
}
function getHobby() {

    let hobby = '';
    $('input:checkbox[name=hobby]').each(function () {

        if ($(this).prop('checked')) {
            hobby += $(this).val() + ',';
        }
    });
    if (hobby != '') {
        hobby = hobby.substring(0, hobby.lastIndexOf(','));
    }
    return hobby;
}

